package io.wdb.modules.generator.generator.service.impl;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;

import io.wdb.common.utils.DateFormatUtil;
import io.wdb.common.utils.HttpClientUtil;
import io.wdb.modules.generator.generator.dao.BookshelfInfoDao;
import io.wdb.modules.generator.generator.dao.BsHeartbeatLogDao;
import io.wdb.modules.generator.generator.entity.BookshelfInfoEntity;
import io.wdb.modules.generator.generator.entity.BsBookshelfWarnEntity;
import io.wdb.modules.generator.generator.entity.BsHeartbeatLogEntity;
import io.wdb.modules.generator.generator.entity.BsSendLogEntity;
import io.wdb.modules.generator.generator.service.BsHeartbeatLogService;
import io.wdb.modules.manager.heart.dao.BsBookshelfWarnDao;
import io.wdb.modules.manager.heart.dao.BsSendLogDao;
import io.wdb.modules.manager.sys.dao.SysUserDao;
import io.wdb.modules.manager.sys.entity.SysUserEntity;



@Service("bsHeartbeatLogService")
public class BsHeartbeatLogServiceImpl implements BsHeartbeatLogService {
	private Logger logger = LoggerFactory.getLogger(BsHeartbeatLogServiceImpl.class);
	
	@Autowired
	private BsHeartbeatLogDao bsHeartbeatLogDao;
	@Autowired
	private BsBookshelfWarnDao bsBookshelfWarnDao;
	@Autowired
	private BookshelfInfoDao bookshelfInfoDao;
	@Autowired
	private SysUserDao sysUserDao;
	@Autowired
	private BsSendLogDao bsSendLogDao;
	@Value("${wx.appid}")
	private String appid;
	
	@Override
	public BsHeartbeatLogEntity queryObject(String bookcaseId){
		return bsHeartbeatLogDao.queryObject(bookcaseId);
	}
	
	@Override
	public List<BsHeartbeatLogEntity> queryList(Map<String, Object> map){
		return bsHeartbeatLogDao.queryList(map);
	}
	
	@Override
	public int queryTotal(Map<String, Object> map){
		return bsHeartbeatLogDao.queryTotal(map);
	}
	
	@Override
	public void save(BsHeartbeatLogEntity bsHeartbeatLog){
		bsHeartbeatLogDao.save(bsHeartbeatLog);
	}
	
	@Override
	public void update(BsHeartbeatLogEntity bsHeartbeatLog){
		bsHeartbeatLogDao.update(bsHeartbeatLog);
	}
	
	@Override
	public void delete(String bookcaseId){
		bsHeartbeatLogDao.delete(bookcaseId);
	}
	
	@Override
	public void deleteBatch(String[] bookcaseIds){
		bsHeartbeatLogDao.deleteBatch(bookcaseIds);
	}
	
	@Override
	public void bookShelfHeartWarn() {
		List<BsHeartbeatLogEntity> bsHeartbeatLogEntities = bsHeartbeatLogDao.queryList(new HashMap<>());
		Date date = new Date();
		for(BsHeartbeatLogEntity bsHeartbeatLogEntity:bsHeartbeatLogEntities) {
			String bookShelfCode = bsHeartbeatLogEntity.getBookcaseId();
			try {
				Date dateDb = bsHeartbeatLogEntity.getTs();
				BsBookshelfWarnEntity bookshelfWarnEntity =  new BsBookshelfWarnEntity();
				bookshelfWarnEntity.setBookshelfCode(bsHeartbeatLogEntity.getBookcaseId());
				if((date.getTime()-dateDb.getTime()>60*1000*6)) {
					bookshelfWarnEntity.setIsdispose(0);
					BsBookshelfWarnEntity bookshelfWarnEntityDb = bsBookshelfWarnDao.queryObjectIsWarn(bookshelfWarnEntity);
					if(bookshelfWarnEntityDb==null) {
						bookshelfWarnEntityDb = bookshelfWarnEntity;
						bookshelfWarnEntityDb.setHeartOutTimes(1);
						bookshelfWarnEntityDb.setCreateTime(date);
						bookshelfWarnEntityDb.setModifyTime(date);
						bookshelfWarnEntityDb.setIssend(0);
						bsBookshelfWarnDao.save(bookshelfWarnEntity);
					}else {
						bookshelfWarnEntityDb.setHeartOutTimes(bookshelfWarnEntityDb.getHeartOutTimes()+1);
						bookshelfWarnEntityDb.setModifyTime(date);
						//达到三次发送报警信息发送报警信息
						if (bookshelfWarnEntityDb.getHeartOutTimes() >= 2 && bookshelfWarnEntityDb.getIssend() == 0) {
							// 反查书柜信息
							BookshelfInfoEntity bookshelfInfoEntity = bookshelfInfoDao
									.queryObject(bsHeartbeatLogEntity.getBookcaseId());
							if (bookshelfInfoEntity == null || bookshelfInfoEntity.getAvailable() == 0) {
								logger.error("书柜信息在主程序中查询不到，或书柜已经不可用");
								continue;
							}
							// 发送报警信息，判断是否符合时间
							if (!this.isInSendTime(date)) {
								logger.info(bookShelfCode+"机柜发送报警信息不符合时间");
								bookshelfWarnEntityDb.setHeartOutTimes(bookshelfWarnEntityDb.getHeartOutTimes()+1);
								bookshelfWarnEntityDb.setModifyTime(date);
								bsBookshelfWarnDao.update(bookshelfWarnEntityDb);
								continue;
							}
							// 发送，
							bookshelfWarnEntityDb.setIssend(1);
							bookshelfWarnEntityDb.setSendtime(date);
							// 根据机柜翻查需要发送的人员
							List<SysUserEntity> sysUserEntities = sysUserDao.queryOpenIdByBookShelfCode(bookShelfCode);
							if (sysUserEntities != null && sysUserEntities.size() > 0) {
								for (SysUserEntity sysUserEntity : sysUserEntities) {
									BsSendLogEntity bsSendLogEntity = new BsSendLogEntity();
									List<NameValuePair> params = new ArrayList<NameValuePair>();
									params.add(new BasicNameValuePair("messageItems",
											"tourser|" + sysUserEntity.getWxPublicOpenId()));
									params.add(new BasicNameValuePair("messageItems",
											"template_id|gvh4FzDXATvJLkRoyhdTvOQlO8uM3PJAGlVQjRlcTfo"));
									params.add(new BasicNameValuePair("messageItems", "url|\"\""));
									params.add(new BasicNameValuePair("messageItems", "appid|wx4aee1144584e2fcd"));
									params.add(new BasicNameValuePair("messageItems", "pagepath|pages/home/home"));
									params.add(new BasicNameValuePair("messageItems",
											"first|" + bookShelfCode + "机柜心跳异常，请知悉。|#173177"));
									params.add(new BasicNameValuePair("messageItems",
											"keyword1|" + bookShelfCode + "机柜心跳异常|#173177"));
									params.add(new BasicNameValuePair("messageItems",
											"keyword2|" + bookshelfInfoEntity.getArea() + "机柜|#173177"));
									params.add(new BasicNameValuePair("messageItems", "keyword3|A059567|#173177"));
									params.add(new BasicNameValuePair("messageItems",
											"keyword4|" + bookShelfCode + "|#173177"));
									params.add(new BasicNameValuePair("messageItems",
											"keyword5|" + bookshelfInfoEntity.getAddress() + "|#173177"));
									params.add(new BasicNameValuePair("messageItems", "remark||#173177"));
									String sendJson = JSONObject.toJSONString(params);
									bsSendLogEntity.setWarnId(bookshelfWarnEntityDb.getId());
									bsSendLogEntity.setUserId(sysUserEntity.getUserId() + "");
									bsSendLogEntity.setSendJson(sendJson);
									String sendJsonRes = HttpClientUtil.getPostBodyDataNameValuePair(
											"http://47.100.117.234:9003/message_service/wx/sendMessage?app_id=" + appid,
											params);
									// bookshelfWarnEntityDb设置关联发送
									bsSendLogEntity.setSendJsonRes(sendJsonRes);
									bsSendLogEntity.setCreateTime(date);
									bsSendLogDao.save(bsSendLogEntity);
								}
							} else {
								logger.error("暂无此书柜负责人员，不发送报警信息");
							}
						}
						bsBookshelfWarnDao.update(bookshelfWarnEntityDb);
					}
				}else {
					BsBookshelfWarnEntity bookshelfWarnEntityDb = bsBookshelfWarnDao.queryObjectIsWarn(bookshelfWarnEntity);
					if(bookshelfWarnEntityDb!=null) {
						bookshelfWarnEntityDb.setIsdispose(1);
						bookshelfWarnEntityDb.setModifyTime(date);
						bookshelfWarnEntityDb.setDisposetime(date);
						bsBookshelfWarnDao.update(bookshelfWarnEntityDb);
					}else {
						continue;
					}
				}
			} catch (Exception e) {
				logger.error(e.getMessage(),e);
			}
		}
	}
	/**
	 * 
	 * @Method:isInSendTime
	 * @Description:是否发送报警信息，true表示发送报警信息
	 * @Time 2018年3月30日 下午5:31:27
	 * @author: Tom
	 * @param date
	 * @return
	 */
	private boolean isInSendTime(Date date) {
		String dateStr = DateFormatUtil.formatDate(date, DateFormatUtil.DATE_PATTERN);
        Date night = DateFormatUtil.parseDatePattern(dateStr+" 21:50:00", DateFormatUtil.DATETIME_PATTERN);
        Date dayTime = DateFormatUtil.parseDatePattern(dateStr+" 08:50:00", DateFormatUtil.DATETIME_PATTERN);;
        Date now = date;
        if(now.after(night)||now.before(dayTime)) {
        	return false;//不发送
        }
		return true;
	}
	public static void main(String[] args) {
		BsHeartbeatLogServiceImpl bsHeartbeatLogServiceImpl = new BsHeartbeatLogServiceImpl();
		Date now = DateFormatUtil.parseDatePattern("2018-03-31 06:00:00", DateFormatUtil.DATETIME_PATTERN);
		System.out.println(bsHeartbeatLogServiceImpl.isInSendTime(now));
	}
	/*public static void main(String[] args) {
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("messageItems", "tourser|oqjm30TzmxrnLII5RuHOaAVFfWqY"));
		params.add(new BasicNameValuePair("messageItems", "template_id|gvh4FzDXATvJLkRoyhdTvOQlO8uM3PJAGlVQjRlcTfo"));
		params.add(new BasicNameValuePair("messageItems", "url|http://weixin.qq.com/download"));
		params.add(new BasicNameValuePair("messageItems", "appid|\"\""));
		params.add(new BasicNameValuePair("messageItems", "pagepath|http://weixin.qq.com/download"));
		params.add(new BasicNameValuePair("messageItems", "first|"+""+"机柜心跳异常，请知悉。|#173177"));
		params.add(new BasicNameValuePair("messageItems", "keyword1|"+"0021200104"+"机柜心跳异常|#173177"));
		params.add(new BasicNameValuePair("messageItems", "keyword2|"+"机柜|#173177"));
		params.add(new BasicNameValuePair("messageItems", "keyword3|A|#173177"));
		params.add(new BasicNameValuePair("messageItems", "keyword4|"+"0021200104|#173177"));
		params.add(new BasicNameValuePair("messageItems", "keyword5|"+"上海市徐汇区石龙路329号越界智慧谷3F|#173177"));
		params.add(new BasicNameValuePair("messageItems", "remark||#173177"));
		List<NameValuePair> formparams = new ArrayList<NameValuePair>();  
        formparams.add(new BasicNameValuePair("messageItems", "touser|oqjm30dXynmpWZG1Hc9TMAOuvVdo"));
        formparams.add(new BasicNameValuePair("messageItems", "template_id|gvh4FzDXATvJLkRoyhdTvOQlO8uM3PJAGlVQjRlcTfo"));
        formparams.add(new BasicNameValuePair("messageItems", "url|http://weixin.qq.com/download"));
        formparams.add(new BasicNameValuePair("messageItems", "appid|xiaochengxuappid12345"));
        formparams.add(new BasicNameValuePair("messageItems", "pagepath|index?foo=bar "));
        formparams.add(new BasicNameValuePair("messageItems", "first|恭喜你购买成功！|#173177"));
        formparams.add(new BasicNameValuePair("messageItems", "keyword1|巧克力|#173177"));
        formparams.add(new BasicNameValuePair("messageItems", "keyword2|巧克力|#173177"));
        formparams.add(new BasicNameValuePair("messageItems", "keyword3|巧克力|#173177"));
        formparams.add(new BasicNameValuePair("messageItems", "keyword4|巧克力|#173177"));
        formparams.add(new BasicNameValuePair("messageItems", "keyword5|巧克力|#173177"));
        formparams.add(new BasicNameValuePair("messageItems", "remark|巧克力|#173177"));
		try {
			String jsonRes = HttpClientUtil.getPostBodyDataNameValuePair("http://47.100.117.234:9003/message_service/wx/sendMessage?app_id=wx555d6fad66f1eb05", params);
			System.out.println(jsonRes);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}*/
}
